package com.shi.yoyoshop.filter;

import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CheckSessionFilter implements Filter {

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    private static final List<String> RELEASE_PATH = new ArrayList<>();


    {
        RELEASE_PATH.add("/yoyoshop/admin/login");
        RELEASE_PATH.add("/yoyoshop/admin/login.jsp");
        RELEASE_PATH.add("/yoyoshop/favicon.ico");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        String requestURI = req.getRequestURI();
        System.out.println("requestURI: " + requestURI);
        // 访问管理端,并且管理端会话存在
        if (!release(requestURI)) {
            if (session != null && session.getAttribute("admin") != null) {
                chain.doFilter(request, response);
            } else {
                String contextPath = req.getContextPath();
                resp.sendRedirect(contextPath + "/yoyoshop/admin/login.jsp");
            }
            return;
        }
        // 可以放行的
        chain.doFilter(request, response);
    }

    /**
     * 判断是否放行该URI
     *
     * @param requestURI
     * @return
     */
    private boolean release(String requestURI) {
        if (RELEASE_PATH.contains(requestURI)) {
            return true;
        }
        if (PATH_MATCHER.match("**/*.jpg", requestURI)) {
            return true;
        }
        if (PATH_MATCHER.match("**/*.js", requestURI)) {
            return true;
        }
        if (PATH_MATCHER.match("**/*.css", requestURI)) {
            return true;
        }
        if (PATH_MATCHER.match("**/*.jsp", requestURI)) {
            return true;
        }
        if (PATH_MATCHER.match("**/*.woff2", requestURI)) {
            return true;
        }
        if (PATH_MATCHER.match("**/*.ttf", requestURI)) {
            return true;
        }
        if (PATH_MATCHER.match("**/*.map", requestURI)) {
            return true;
        }
        return !PATH_MATCHER.match("/yoyoshop/admin/**", requestURI);
    }
}
